layui.define(['jquery','table'], function (exports) {

    var $ = layui.jquery,
    table = layui.table

    function add0(m) {
        return m < 10 ? '0' + m : m
    }
    function mou (obj) {
        if (obj >= 0 && obj <= 9) {
            obj = "0" + obj;
        }
        return obj;
    };

    //获取登录信息
    var user = getUser();
    var token;
    try{
        token = user.token;
    }catch(error){
        console.log(error);
    }

    //登录超时处理
    // $.ajaxSetup({
    //     type:"post",
    //     dataType:"json",
    //     cache:false,
    //     contentType:"application/json",
    //     complete:function(xhr,status){
    //         var responseHeader = xhr.getResponseHeader('sessionstatus');
    //         if(responseHeader=='timeout'){
    //             layer.confirm('请求超时！请稍后再试！！！', {
    //                 icon: 8,
    //                 title:'提示',
    //                 btn: ['知道了'],
    //                 closeBtn: false,
    //             }, function(index){
    //                 layer.close(index);
    //                 window.open ('../login.jsp','_top')
    //             });
    //         }else if(responseHeader=="seesionInexistence"){
    //             layer.confirm('登录超时！请重新登录！！！', {
    //                 icon: 8,
    //                 title:'提示',
    //                 btn: ['知道了'],
    //                 closeBtn: false,
    //             }, function(index){
    //                 layer.close(index);
    //                 window.open ('../login.jsp','_top')
    //             });
    //         }else if(status == "success"){
    //             try{
    //                 var data = JSON.parse(xhr.responseText);
    //                 if(data.status && data.status != "1000"){
    //                     //alert("");//layer.alert("程序出错了，请赶紧联系程序员GG！错误代码:"+data.status);
    //                 }
    //             }catch(e){
    //                 console.log("非标准格式的ajax请求");
    //             }
    //         }
    //         console.log("responseHeader==>"+responseHeader);
    //     }
    // });
    //获取url里面的参数
    // function getParameterByName (paramName) {
    //     var args = new Object();
    //     var argsStr = location.search;  //获取URL参数字符串
    //     if (argsStr.length > 0) {
    //         argsStr = argsStr.substring(1);
    //         var nameValueArr = argsStr.split("&");  //多参数
    //         for (var i = 0; i < nameValueArr.length; i++) {
    //             var pos = nameValueArr[i].indexOf('=');
    //             if (pos == -1) continue; //如果没有找到就跳过
    //             var argName = nameValueArr[i].substring(0, pos); //提取name
    //             var argVal = nameValueArr[i].substring(pos + 1); //提取value
    //             args[argName] = unescape(argVal);
    //         }
    //         return args[paramName];
    //     }
    // };

    var obj = {
        ajax: function ajax(url, data, success,type,async, error) {
            var type = type || 'post';//请求类型
            var async = async || true;//异步请求
            var success = success || function (data) {
                    /*console.log('请求成功');*/
                    setTimeout(function () {
                        layer.msg(data.msg);
                    }, 500);
                    if (data.status) {//服务器处理成功
                        // setTimeout(function () {
                        //     if (data.url) {
                        //         location.replace(data.url);
                        //     } else {
                        //         location.reload(true);
                        //     }
                        // }, 1500);
                    } else {//服务器处理失败
                        layer.msg(data.msg, {icon: 5, shade: 0.01});
                    }
                };
            var error = error || function (data) {
                    // console.error('请求成功失败');
                    /*data.status;//错误状态吗*/
                    try {
                        $.hideIndicator();
                    } catch (error) {
                        layer.closeAll('loading');
                    }
                    setTimeout(function () {
                        console.log(data.status)
                        console.log(data.data)

						
                        switch (data.status) {
                            case 400:
                                data.message = '请求错误';
                                break;
                            case 401:
                                data.message = '未授权，请登录';
                                break;
                            case 403:
                                data.message = '拒绝访问';
                                break;
                            case 404:
                                data.message = '请求地址出错';
                                break;
                            case 408:
                                data.message = '请求超时';
                                break;
                            case 500:
                                data.message = '服务器内部错误';
                                break;
                            case 501:
                                data.message = '服务未实现';
                                break;
                            case 502:
                                data.message = '网关错误';
                                break;
                            case 503:
                                data.message = '服务不可用';
                                break;
                            case 504:
                                data.message = '网关超时';
                                break;
                            case 505:
                                data.message = 'HTTP版本不受支持';
                                break;
                            case 0:
                                data.message = '连接被拒';
                                break;
                            default:
                        }
                        layer.msg(data.message);
                    }, 500);
                };


            $.ajax({
                'url': url,
                'data': data,
                'type': type,
                'dataType': 'json',
                'async': async,
                'success': success,
                'contentType': "application/json",
                'error': error,
                'jsonpCallback': 'jsonp' + (new Date()).valueOf().toString().substr(-4),
                'beforeSend': function () {
                    try {
                        $.showIndicator()
                    } catch (error) {
                        // layer.load(0, {shade: false});
                    }
                },
                'headers':{
                    'token': token
                }
            });
        },
        //弹窗
        open: function (title, div, wh, btn, fun, fun1) {
            layer.open({
                type: 1,
                shade: false,
                area: wh,
                btn: btn,
                title: title,
                content: div,
                maxmin: true,
                yes: function (index, layero) {
                    if (fun) {
                        fun(index)
                    }
                },
                btn2: function (index, layero) {
                    if (fun1) {
                        fun1(index)
                    }
                }
            })
        },
        goPAGE: function (type, wardId, userId, empName, roles) {
            var us = sessionStorage.getItem('us');
            us = JSON.parse(us);
            if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
                type = getParameterByName('type');
                wardId = getParameterByName('wardId');
                userId = getParameterByName('userId');
                sessionStorage.setItem('wardId',wardId);
                sessionStorage.setItem('userId',userId);
                return [type, wardId, userId];
            } else {
                type = getParameterByName('type');
                if (us) {
                    wardId = us.wards;
                    userId = us.id;
                    empName = us.empName;
                    roles = us.roles;
                    return [type, wardId, userId, empName, roles]
                } else {
                    return [];
                }
            }
        },
        getNowFormat: function () {
            var date = new Date();

            var seperator1 = "-";
            var seperator2 = ":";
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            var currentdate = date.getFullYear() + seperator1 + mou(month) + seperator1 + mou(strDate)
                + " " + mou(date.getHours()) + seperator2 + mou(date.getMinutes())
                + seperator2 + mou(date.getSeconds());
            return currentdate;
        },

        lessDate: function (num,m,y) {
            var date1 = new Date();
            var date2 = new Date(date1);
            date2.setDate(date1.getDate() - num || 30);
            var month = date2.getMonth() + (m == undefined ? 1 : m);
            if(date1.getDate() - num === 0){
                month = month-1
            }
            var Year = date2.getFullYear() - y || date2.getFullYear();
            return (Year + "-" + add0(month) + "-" + add0(date2.getDate()))
        },

        //时间戳
        format: function format(shijianchuo) {
            var time = new Date(shijianchuo);
            var y = time.getFullYear();
            var m = time.getMonth() + 1;
            var d = time.getDate();
            var h = time.getHours();
            var mm = time.getMinutes();
            var s = time.getSeconds();
            return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
        },

        //数据表格
        table:function(elem,url,where,arr,limit,method,fun,toolbar,defaultToolbar,title){
            table.render({
                elem: elem              //table表格
                ,toolbar: toolbar       //头部操作栏
                ,url:url
                ,where:where            //{taskType:0} 提交数据
                ,contentType: 'application/json'
                ,method:method          //请求方式
                ,limit:limit            //每页条数
                ,defaultToolbar:defaultToolbar  //头部功能显示
                ,loading:true
                ,parseData:function(res){
                    if (fun) {
                        return fun(res)
                    }
                }
                ,request: {
                    pageName: 'currPage'       //页码的参数名称，默认：page
                    ,limitName: 'pageSize' //页码的参数名称，默认：page

                }
                ,response: {
                    countName: 'total' //规定数据总数的字段名称，默认：count
                }
                ,title: title || ''
                ,cols:arr
                ,page: true
                ,headers:{
                    token:token
                }
            });
        },
    };

    //输出接口
    exports('commons', obj);


    /**时间格式化工具
     * 如:
     *      new Date().format("yyyy-MM-dd hh:mm:ss")
     *      new Date().format("yyyy-MM-dd ")
     * */
    Date.prototype.format = function (format) {
        var args = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
            "S": this.getMilliseconds()
        };
        if (/(y+)/.test(format))
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var i in args) {
            var n = args[i];
            if (new RegExp("(" + i + ")").test(format))
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? n : ("00" + n).substr(("" + n).length));
        }
        return format;

    };


    /**
     *获取当前登录用户
     * @returns {any} json对象
     */
    function getUser(){
        //获取登录信息
        var user = JSON.parse(window.sessionStorage.getItem("user"));
        return user;
    }

    /**
     * 包装成标准的请求接口参数
     * @param data
     */
    function formatData(data) {
        var tableData = {
            "body":{
            },
            "header":{
            },
            "token":{
            }
        };
        tableData.body = data;
        return tableData;
    }
});
